<template>
  <div class="employees-container">
    <div class="header">
      <h3>员工管理</h3>
      <el-button type="primary" @click="handleAdd">
        <el-icon><Plus /></el-icon>添加员工
      </el-button>
    </div>

    <el-table :data="employees" style="width: 100%" v-loading="loading">
      <el-table-column prop="employeeId" label="员工ID" width="120" />
      <el-table-column prop="name" label="姓名" width="120" />
      <el-table-column prop="position" label="职位" width="120" />
      <el-table-column prop="department.name" label="所属部门" />
      <el-table-column prop="salary" label="薪资" width="120">
        <template #default="{ row }">
          {{ row.salary }} 元
        </template>
      </el-table-column>
      <el-table-column label="操作" width="200">
        <template #default="{ row }">
          <el-button-group>
            <el-button type="primary" @click="handleEdit(row)">
              <el-icon><Edit /></el-icon>编辑
            </el-button>
            <el-button type="danger" @click="handleDelete(row)">
              <el-icon><Delete /></el-icon>删除
            </el-button>
          </el-button-group>
        </template>
      </el-table-column>
    </el-table>

    <el-dialog
      v-model="dialogVisible"
      :title="dialogType === 'add' ? '添加员工' : '编辑员工'"
      width="500px"
    >
      <el-form
        ref="formRef"
        :model="form"
        :rules="rules"
        label-width="100px"
      >
        <el-form-item label="员工ID" prop="employeeId">
          <el-input v-model="form.employeeId" :disabled="dialogType === 'edit'" />
        </el-form-item>
        <el-form-item label="姓名" prop="name">
          <el-input v-model="form.name" />
        </el-form-item>
        <el-form-item label="职位" prop="position">
          <el-input v-model="form.position" />
        </el-form-item>
        <el-form-item label="地址" prop="address">
          <el-input v-model="form.address" />
        </el-form-item>
        <el-form-item label="所属部门" prop="departmentId">
          <el-select v-model="form.departmentId" placeholder="请选择部门">
            <el-option
              v-for="department in departments"
              :key="department.departmentId"
              :label="department.name"
              :value="department.departmentId"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="薪资" prop="salary">
          <el-input-number v-model="form.salary" :min="0" :precision="2" />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleSubmit">确定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { Plus, Edit, Delete } from '@element-plus/icons-vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import api from '../api'

const employees = ref([])
const departments = ref([])
const loading = ref(false)
const dialogVisible = ref(false)
const dialogType = ref('add')
const formRef = ref(null)

const form = ref({
  employeeId: '',
  name: '',
  position: '',
  address: '',
  departmentId: '',
  salary: null
})

const rules = {
  employeeId: [
    { required: true, message: '请输入员工ID', trigger: 'blur' },
    { min: 1, max: 10, message: '长度在 1 到 10 个字符', trigger: 'blur' }
  ],
  name: [
    { required: true, message: '请输入员工姓名', trigger: 'blur' },
    { min: 1, max: 50, message: '长度在 1 到 50 个字符', trigger: 'blur' }
  ],
  position: [
    { max: 50, message: '长度不能超过 50 个字符', trigger: 'blur' }
  ],
  address: [
    { max: 200, message: '长度不能超过 200 个字符', trigger: 'blur' }
  ],
  departmentId: [
    // 移除必填验证
  ],
  salary: [
    { type: 'number', message: '薪资必须为数字', trigger: 'blur' }
  ]
}

const loadData = async () => {
  loading.value = true
  try {
    employees.value = await api.get('/employees')
    departments.value = await api.get('/departments')
  } catch (error) {
    ElMessage.error('加载数据失败')
  }
  loading.value = false
}

const handleAdd = () => {
  dialogType.value = 'add'
  form.value = {
    employeeId: '',
    name: '',
    position: '',
    address: '',
    departmentId: '',
    salary: null
  }
  dialogVisible.value = true
}

const handleEdit = (row) => {
  dialogType.value = 'edit'
  form.value = {
    employeeId: row.employeeId,
    name: row.name,
    position: row.position,
    address: row.address,
    departmentId: row.department?.departmentId || '',
    salary: row.salary
  }
  dialogVisible.value = true
}

const handleDelete = (row) => {
  ElMessageBox.confirm(
    '确定要删除该员工吗？',
    '警告',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }
  ).then(async () => {
    try {
      await api.delete(`/employees/${row.employeeId}`)
      ElMessage.success('删除成功')
      loadData()
    } catch (error) {
      ElMessage.error('删除失败')
    }
  })
}

const handleSubmit = async () => {
  if (!formRef.value) return
  await formRef.value.validate(async (valid) => {
    if (valid) {
      try {
        const submitData = {
          employeeId: form.value.employeeId,
          name: form.value.name,
          position: form.value.position || '',
          address: form.value.address || '',
          salary: form.value.salary,
          department: form.value.departmentId ? { departmentId: form.value.departmentId } : null
        }
        if (dialogType.value === 'add') {
          await api.post('/employees', submitData)
          ElMessage.success('添加成功')
        } else {
          await api.put(`/employees/${form.value.employeeId}`, submitData)
          ElMessage.success('更新成功')
        }
        dialogVisible.value = false
        loadData()
      } catch (error) {
        console.error('操作失败:', error)
        const errorMessage = error.response?.data?.message || error.response?.data?.position || (dialogType.value === 'add' ? '添加失败' : '更新失败')
        ElMessage.error(errorMessage)
      }
    }
  })
}

onMounted(() => {
  loadData()
})
</script>

<style scoped>
.employees-container {
  padding: 20px;
  background-color: #fff;
  border-radius: 4px;
}

.header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
}
</style> 